const express = require('express')
const app = express()
const db = require('../apis/connectMongo')

let blogSchema = new db.Schema({
    author:       {type: String},   //  博客作者的username
    content:      {type: String},
    dateTime:     {type: String},
    lookNumber:   {type: Number, default: 0},
    likeNumber:   {type: Number, default: 0},
    commentNumber:{type: Number, default: 0}
}, {collection: 'blog'})       

let blogModel = db.model('blogModel', blogSchema)

module.exports = {
  //  创建记录
  createBlog: async (author, content, dateTime) => {
    try {
      await blogModel.create({
        'author':   author,  
        'content':  content,
        'dateTime': dateTime
      })
    } catch (err) {
      console.log(err)
    }
  },
  findBlog: async (author, content) => {
    try {
      let docs = await blogModel.findOne({
        'author':   author,  
        'content':  content
      })
      return docs
    } catch (err) {
      console.log(err)
    }
  },
  findBlogByAuthor: async (author) => {
    try {
      let docs = await blogModel.find({
        'author':   author
      })
      return docs
    } catch (err) {
      console.log(err)
    }
  },
  //  获取最新的博客
  findBlogByDateTime: async () => {
    try {
      let docs = await blogModel.find({}, null, {sort: {"dateTime": -1}}, function(err, docs) {   //  1为升序, -1为降序
        console.log(docs);
      })
      return docs
    } catch (err) {
      console.log(err)
    }
  }
}